package electricity.service.impl;
import cn.dev33.satoken.stp.StpUtil;
import electricity.domain.Role;
import electricity.domain.SysUser;
import electricity.dto.UserDto;
import electricity.jwtutils.JwtUtils;
import electricity.mapper.RoleMapper;
import electricity.mapper.SysUserMapper;
import electricity.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
@Slf4j
public class LoginServiceImpl  implements LoginService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private RoleMapper roleMapper;

    /**
     * 登录
     * @param userDto
     * @return
     */
   // @Transactional
    public String login(UserDto userDto) {
        log.info("用户登录：{}", userDto);
        // 1. 将前端传递的角色字符串转为Integer
        Integer roleType =Integer.valueOf(userDto.getRole_type());
        // 2. 调用Mapper查询用户
        SysUser sysUser = sysUserMapper.selectByUsernameAndRole(userDto.getUsername(),roleType);
        // 3. 验证用户是否存在
        if (sysUser == null) {
            log.warn("用户不存在：{}", userDto.getUsername());
            throw new RuntimeException("用户不存在");
        }
        //验证密码
        if(!sysUser.getPassword().equals(userDto.getPassword())){
            log.warn("密码错误：{}", userDto.getUsername());
            throw new RuntimeException("密码错误");
        }
        // 5. 生成JWT Token
        String token = JwtUtils.getToken(userDto.getUsername());
        log.info("用户登录成功: {}", userDto.getUsername());

        return token;
    }

    @Override
    public SysUser selectByUsername(String username) {
        return sysUserMapper.selectByUsername(username);
    }

    @Override
    public boolean login(String username, String password) {
        SysUser sysUser = selectByUsername(username);
        if (sysUser != null  && Objects.equals(sysUser.getPassword(), password)) {
            // 登录成功，使用Sa - token记录登录状态
            StpUtil.login(sysUser.getId(),30 * 24 * 60 * 60);
            // 获取用户角色ID
            Integer roleId = roleMapper.selectRoleIdByUserId(sysUser.getId());
            if (roleId != null) {
                Role role = roleMapper.selectById(roleId);
                if (role != null) {
                    // 将角色名存入Sa - token
                    StpUtil.getSession().set("role", role.getRoleName());
                }
            }
            return true;
        }
        return false;
    }

}
